#include "chatserver.hpp"
#include "json.hpp"
#include "chatservice.hpp"

#include <functional>

using namespace std;
using namespace std::placeholders;

using json = nlohmann::json;

//初始化server，注册回调
chatServer::chatServer(EventLoop *loop,
                       const InetAddress &listenAddr,
                       const string &nameArg) : ser_(loop, listenAddr, "chatServer")
{
    ser_.setConnectionCallback(
        std::bind(&chatServer::onConnection, this, _1));
    ser_.setMessageCallback(
        std::bind(&chatServer::onMessage, this, _1, _2, _3));
}

void chatServer::start()
{
    ser_.start();
}

void chatServer::onConnection(const TcpConnectionPtr &conn)
{
    if(!conn->connected()) {
        ChatService::instance()->connCloseException(conn);
        conn->shutdown();
    }
}

void chatServer::onMessage(const TcpConnectionPtr &conn, Buffer *buffer, Timestamp time)
{
    json js = json::parse(buffer->retrieveAllAsString());
    //解析json数据并根据请求类型执行任务
    auto msgHandler = ChatService::instance()->getHandler(js["msgid"].get<int>());
    msgHandler(conn, js, time);
}